<template>
  <view class="content-box">
    <view class="content">
      <view>
        <uv-calendars mode="range" ref="calendars" allowSameDay @confirm="confirmCalendars" rangePrompt="31"/>
      </view>
      <uv-sticky bgColor="#fff">
        <view class="date-filter">
                     <view class="date-row">
             <uv-tags borderColor="#3c9cff" type="primary" @click="openCalendars" text="日期:"
                      icon="calendar" plain></uv-tags>
             <uv-text type="primary" :text="rangeData" @click="openCalendars" class="date-text"></uv-text>
             <uv-tags v-if="rangeData" borderColor="#ff6b6b" type="error" text="重置" plain @click="restCalendars"></uv-tags>
           </view>

           <view class="search-box">
             <uv-search 
               @change="changeFn" 
               placeholder="请输入姓名" 
               :show-action="false" 
               :border="false" 
               bgColor="#f8f9fa"
               borderColor="#e9ecef"
               v-model="queryParams.userName" 
               shape="square" 
               :clearabled="true" 
               @clear="clear"
             ></uv-search>
           </view>
        </view>
      </uv-sticky>

      <mescroll-body @init="mescrollInit" @down="downCallback" @up="upCallback">
        <view class="list-container">
                     <view class="list-row" v-for="(row, rowIndex) in chunkedDataList" :key="rowIndex">
             <view class="list-item" v-for="(item, index) in row" :key="index" @click="item && goDetail(item)" v-if="item">
              <view class="flex">
                <uv-text :lines="2" :text="item.userName"></uv-text>
                <uv-tags
                    v-for="typeItem in typeData"
                    :key="typeItem.dictKey"
                    v-if="item.type == typeItem.dictKey"
                    :text="typeItem.dictValue"
                    :type="typeItem.listClass"
                    size="mini"
                    plain
                ></uv-tags>
              </view>
              <view class="flex">
                <view class="text-gray">日期：</view>
                <view class="text-gray">{{ item.time }}</view>
              </view>
              <view class="flex">
                <view class="text-gray">备注：</view>
                <view class="text-gray remark-text">{{item.remark || '无'}}</view>
              </view>
            </view>
          </view>
                 </view>
       </mescroll-body>
     </view>
     
                 <!-- 考勤详情弹窗 -->
      <uv-popup ref="detailPopup" mode="bottom" :round="10" :closeable="true" @close="closeDetailPopup" @change="onPopupChange">
        <view class="detail-popup" v-if="currentDetail">
          <!-- 头部区域 -->
          <view class="detail-header">
            <view class="header-title">
              <text class="title-text">考勤详情</text>
            </view>
                         <view class="header-status">
               <uv-tags
                 v-for="typeItem in typeData"
                 :key="typeItem.dictKey"
                 v-if="currentDetail.type == typeItem.dictKey"
                 :text="typeItem.dictValue"
                 :type="typeItem.listClass"
                 size="mini"
                 plain
                 class="status-tag"
               ></uv-tags>
             </view>
          </view>
          
          <!-- 主要内容区域 -->
          <view class="detail-content">
            <!-- 基本信息卡片 -->
            <view class="info-card">
              <view class="card-title">
                <text class="card-title-text">基本信息</text>
              </view>
              <view class="info-grid">
                <view class="info-item">
                  <view class="info-label">
                    <text class="label-icon">👤</text>
                    <text class="label-text">姓名</text>
                  </view>
                  <view class="info-value">{{ currentDetail.userName }}</view>
                </view>
                
                <view class="info-item">
                  <view class="info-label">
                    <text class="label-icon">📅</text>
                    <text class="label-text">日期</text>
                  </view>
                  <view class="info-value">{{ currentDetail.time }}</view>
                </view>
                
                <view class="info-item" v-if="currentDetail.createTime">
                  <view class="info-label">
                    <text class="label-icon">⏰</text>
                    <text class="label-text">创建时间</text>
                  </view>
                  <view class="info-value">{{ currentDetail.createTime }}</view>
                </view>
              </view>
            </view>
            
            <!-- 备注信息卡片 -->
            <view class="info-card" v-if="currentDetail.remark">
              <view class="card-title">
                <text class="card-title-text">备注信息</text>
              </view>
              <view class="remark-content">
                <text class="remark-text">{{ currentDetail.remark }}</text>
              </view>
            </view>
          </view>
          
          <!-- 底部按钮区域 -->
          <view class="detail-footer">
            <view class="footer-buttons">
              <button class="btn-secondary" @click="closeDetailPopup">关闭</button>
              <button class="btn-primary" @click="handleEdit">编辑</button>
            </view>
          </view>
        </view>
      </uv-popup>
    </view>
  </template>

<script>
import MescrollMixin from "@/uni_modules/mescroll-uni/components/mescroll-uni/mescroll-mixins.js";
import UserSalaryDayAPI from '@/api/usersalaryday'
import {dateFormat, getOffsetTime} from "@/utils/media";
import DictAPI from "@/api/dict";

export default {
  mixins: [MescrollMixin], // 使用mixin
  comments: {},
  data() {
    return {
      current: 0,
      queryParams: {
        current: 1,
        size: 20,
        startTime: '',
        endTime: ''
      },
      dataList: [],
      total: 0,
      show: false,
      form: {},
      authority: 'employee', // admin、employee、purchase、employee_manager、purchase_manager
      id: '',
      rangeData: '',
      answerInfo: {},
      columns: [],
      typeData: [],
             screenWidth: 0,
       cardWidth: 0,
       currentDetail: null,
    }
  },
  onLoad(e) {
    if (e.createDept) {
      this.queryParams.createDept = e.createDept
    }
    this.authority = uni.getStorageSync('authInfo')?.authority

    // 获取屏幕尺寸并计算卡片宽度
    this.getScreenInfo()

    // 默认日期范围
    const afterTime = new Date();
    this.queryParams.startTime = dateFormat(afterTime, 'yyyy-MM-dd')
    this.queryParams.endTime = dateFormat(afterTime, 'yyyy-MM-dd')
    this.rangeData = this.queryParams.startTime + ' ~ ' + this.queryParams.endTime

    this.init()
  },
  computed: {
    // 将数组按每两个元素为一组的方式进行分组
    chunkedDataList() {
      const chunkSize = 2;
      const result = [];
      for (let i = 0; i < this.dataList.length; i += chunkSize) {
        const chunk = this.dataList.slice(i, i + chunkSize);
        // 如果最后一行只有一个元素，添加一个空占位符
        if (chunk.length === 1 && i + chunkSize >= this.dataList.length) {
          chunk.push(null);
        }
        result.push(chunk);
      }
      return result;
    }
  },
  methods: {
    // 获取屏幕信息并计算卡片宽度
    getScreenInfo() {
      const systemInfo = uni.getSystemInfoSync()
      this.screenWidth = systemInfo.screenWidth
      // 计算卡片宽度：屏幕宽度 - 左右边距(40rpx) - 卡片间距(20rpx) - 容器内边距(40rpx)
      const totalPadding = 40 + 20 + 40 // rpx
      const availableWidth = this.screenWidth - (totalPadding * 2) // 转换为px
      this.cardWidth = (availableWidth - 20) / 2 // 减去卡片间距，除以2得到单个卡片宽度
    },
    
    init() {
      DictAPI.dictByCodeList({
        code: 'attendance_type'
      }).then(res => {
        this.typeData = [...res.data]
      })
    },
    goDetail(item) {
      console.log('点击了', item);
      this.currentDetail = item;
      
      // 添加 toast 确认方法被调用
      uni.showToast({
        title: '点击成功',
        icon: 'success',
        duration: 1000
      });
      
      // 使用 ref 调用 uv-popup 的 open 方法
      this.$nextTick(() => {
        this.$refs.detailPopup.open('bottom');
      });
    },
    

    
    getTypeText(type) {
      const typeItem = this.typeData.find(item => item.dictKey == type);
      return typeItem ? typeItem.dictValue : '未知';
    },
    
    closeDetailPopup() {
      this.$refs.detailPopup.close();
      this.currentDetail = null;
    },
    
    onPopupChange(e) {
      console.log('弹窗状态改变：', e);
    },
    
    handleEdit() {
      // 这里可以添加编辑功能
      uni.showToast({
        title: '编辑功能开发中',
        icon: 'none'
      });
    },
    openCalendars() {
      this.$refs.calendars.open();
    },
    confirmCalendars(e) {
      let me = this;
      console.log(e)
      me.rangeData = e.range.before + ' ~ ' + e.range.after

      me.queryParams.current = 1
      me.queryParams.startTime = e.range.before
      me.queryParams.endTime = e.range.after
      me.dataList = []
      //(内部会自动page.num=1,再主动触发up.callback)
      this.mescroll.resetUpScroll();
    },
    restCalendars() {
      let me = this;
      me.rangeData = ''
      me.queryParams.current = 1
      me.queryParams.startTime = ''
      me.queryParams.endTime = ''
      me.dataList = []
      //(内部会自动page.num=1,再主动触发up.callback)
      this.mescroll.resetUpScroll();
    },

    /*上拉加载的回调*/
    upCallback(page) {
      let me = this
      me.queryParams.current = page.num; // 页码, 默认从1开始
      UserSalaryDayAPI.list(me.queryParams).then(res => {
        let curPageData = res.data.records
        // 接口返回的当前页数据长度 (如列表有26个数据,当前页返回8个,则curPageLen=8)
        let curPageLen = curPageData.length;
        // 接口返回的总页数 (如列表有26个数据,每页10条,共3页; 则totalPage=3)
        let totalPage = res.data.totalPage
        me.total = res.data.total
        //设置列表数据
        if (page.num === 1) this.dataList = []; //如果是第一页需手动置空列表

        this.dataList = this.dataList.concat(curPageData); //追加新数据

        // 请求成功,隐藏加载状态
        //方法一(推荐): 后台接口有返回列表的总页数 totalPage
        this.mescroll.endByPage(curPageLen, totalPage);
      })
    },
    changeFn() {
      let me = this;
      me.queryParams.current = 1
      me.dataList = []
      //(内部会自动page.num=1,再主动触发up.callback)
      this.mescroll.resetUpScroll();
    },
    clear() {
      this.queryParams = {
        current: 1,
        size: 10
      }
      this.dataList = []
      //(内部会自动page.num=1,再主动触发up.callback)
      this.mescroll.resetUpScroll();
    },
  }
}
</script>

<style scoped lang="scss">
.content-box {
  background-color: #f5f5f5;
  min-height: 100vh;
}

.content {
  padding: 20rpx;
  width: 100%;
  box-sizing: border-box;
  overflow: hidden;
}

.list-container {
  display: flex;
  flex-direction: column;
  gap: 20rpx;
  margin-top: 20rpx;
  width: 100%;
  box-sizing: border-box;
}

.list-row {
  display: flex;
  gap: 20rpx;
  justify-content: space-between;
  flex-wrap: nowrap;
  width: 100%;
}

.list-item {
  width: calc(50% - 10rpx);
  background-color: #ffffff;
  padding: 30rpx 20rpx;
  border-radius: 16rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.08);
  border: 2rpx solid #f0f0f0;
  transition: all 0.3s ease;
  box-sizing: border-box;
  
  &:active {
    transform: scale(0.98);
    box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.12);
  }
}

.list-item .flex {
  display: flex;
  align-items: center;
  margin-bottom: 16rpx;
  
  &:last-child {
    margin-bottom: 0;
  }
}

.list-item .flex:first-child {
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 20rpx;
  
  .uv-text {
    flex: 1;
    font-size: 32rpx;
    font-weight: 500;
    color: #333;
    line-height: 1.4;
  }
  
  .uv-tags {
    margin-left: 16rpx;
    flex-shrink: 0;
  }
}

.text-gray {
  font-size: 28rpx;
  color: #666;
  line-height: 1.5;
  
  &:first-child {
    min-width: 80rpx;
    flex-shrink: 0;
  }
  
  &:last-child {
    flex: 1;
    text-align: right;
    word-break: break-all;
    white-space: normal;
  }
}

.remark-text {
  max-width: 200rpx;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.date-filter {
  padding: 20rpx;
  background-color: #ffffff;
  border-bottom: 2rpx solid #f0f0f0;
}

.date-row {
  display: flex;
  align-items: center;
  gap: 20rpx;
  margin-bottom: 20rpx;
  flex-wrap: nowrap;
  
  .date-text {
    flex: 1;
    font-size: 28rpx;
    color: #3c9cff;
    font-weight: 500;
    white-space: nowrap;
  }
}

.search-box {
  margin: 0;
  width: 100%;
  
  :deep(.uv-search) {
    width: 100%;
  }
  
  :deep(.uv-search__content) {
    width: 100%;
  }
}

/* 响应式设计 */
@media screen and (max-width: 750rpx) {
  .list-row {
    flex-direction: column;
    gap: 16rpx;
  }
  
  .list-item {
    width: 100%;
    flex: none;
  }
  
  .date-row {
    flex-wrap: wrap;
    gap: 10rpx;
  }
}

/* 小屏幕设备优化 */
@media screen and (max-width: 600rpx) {
  .content {
    padding: 16rpx;
  }
  
  .list-container {
    gap: 16rpx;
  }
  
  .list-row {
    gap: 16rpx;
  }
  
  .list-item {
    padding: 24rpx 16rpx;
  }
  
     .date-filter {
     padding: 16rpx;
   }
 }
 
     /* 详情弹窗样式 - 简洁版本 */
  .detail-popup {
    padding: 0;
    max-height: 85vh;
    overflow-y: auto;
    background-color: #ffffff;
    border-radius: 20rpx 20rpx 0 0;
    min-height: 500rpx;
  }
  
  /* 头部区域 - 简洁设计 */
  .detail-header {
    padding: 30rpx;
    background-color: #ffffff;
    border-bottom: 1rpx solid #e5e5e5;
    position: relative;
  }
  
  .header-title {
    text-align: center;
    margin-bottom: 16rpx;
  }
  
  .title-text {
    font-size: 32rpx;
    font-weight: 600;
    color: #333333;
  }
  
  .header-status {
    text-align: center;
    
    .status-tag {
      display: inline-block;
      padding: 4rpx 12rpx;
      font-size: 24rpx;
      border-radius: 4rpx;
      border: 1rpx solid;
      background-color: transparent;
      
      /* 根据不同类型设置不同的颜色 */
      &.uv-tags--primary {
        color: #3c9cff;
        border-color: #3c9cff;
      }
      
      &.uv-tags--success {
        color: #19be6b;
        border-color: #19be6b;
      }
      
      &.uv-tags--warning {
        color: #f0ad4e;
        border-color: #f0ad4e;
      }
      
      &.uv-tags--error {
        color: #fa3534;
        border-color: #fa3534;
      }
    }
  }
  
  /* 主要内容区域 */
  .detail-content {
    padding: 30rpx;
  }
  
  /* 信息卡片 - 简洁设计 */
  .info-card {
    background: #ffffff;
    border-radius: 8rpx;
    padding: 20rpx;
    margin-bottom: 20rpx;
    border: 1rpx solid #e5e5e5;
  }
  
  .card-title {
    margin-bottom: 16rpx;
    padding-bottom: 12rpx;
    border-bottom: 1rpx solid #e5e5e5;
  }
  
  .card-title-text {
    font-size: 28rpx;
    font-weight: 600;
    color: #333333;
  }
  
  /* 信息网格 */
  .info-grid {
    display: flex;
    flex-direction: column;
    gap: 16rpx;
  }
  
  .info-item {
    display: flex;
    align-items: center;
    padding: 12rpx 0;
  }
  
  .info-label {
    display: flex;
    align-items: center;
    min-width: 160rpx;
    flex-shrink: 0;
  }
  
  .label-icon {
    font-size: 24rpx;
    margin-right: 8rpx;
    color: #666666;
  }
  
  .label-text {
    font-size: 28rpx;
    color: #666666;
    font-weight: 400;
  }
  
  .info-value {
    flex: 1;
    font-size: 28rpx;
    color: #333333;
    font-weight: 400;
    text-align: right;
  }
  
  /* 备注内容 - 简洁设计 */
  .remark-content {
    padding: 16rpx;
    background-color: #f9f9f9;
    border-radius: 6rpx;
    border-left: 4rpx solid #cccccc;
  }
  
  .remark-text {
    font-size: 28rpx;
    color: #333333;
    line-height: 1.5;
    word-break: break-all;
  }
  
  /* 底部按钮区域 - 简洁设计 */
  .detail-footer {
    padding: 30rpx;
    background-color: #ffffff;
    border-top: 1rpx solid #e5e5e5;
  }
  
  .footer-buttons {
    display: flex;
    gap: 16rpx;
  }
  
  .btn-secondary, .btn-primary {
    flex: 1;
    padding: 20rpx;
    border-radius: 6rpx;
    font-size: 28rpx;
    font-weight: 400;
    border: none;
    transition: all 0.2s ease;
  }
  
  .btn-secondary {
    background-color: #f5f5f5;
    color: #666666;
    border: 1rpx solid #e5e5e5;
    
    &:active {
      background-color: #e5e5e5;
    }
  }
  
  .btn-primary {
    background-color: #007aff;
    color: #ffffff;
    
    &:active {
      background-color: #0056cc;
    }
  }
 </style>